package com.cbtx.networklib.util

import android.text.TextUtils
import okhttp3.Request
import okio.Buffer
import java.io.IOException
import java.net.URLDecoder
import java.util.*

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/2 3:07 PM
 * desc   :
 */
object SignUtil {
    @Throws(IOException::class)

    fun getSign(originalRequest: Request, currentTime: Long): String {
        val body = originalRequest.body
        val postPath = originalRequest.url.toUrl().file
        val buffer = Buffer()
        body?.writeTo(buffer)
        var oldParamsJson = buffer.readUtf8()
        oldParamsJson = URLDecoder.decode(oldParamsJson)
        val paramNames: MutableSet<String> =
            TreeSet() // 使用treeset 自然排序

        // 如果老参数不为空，自然排序
        if (!TextUtils.isEmpty(oldParamsJson)) {
            val params = oldParamsJson.split("&".toRegex()).toTypedArray()
            for (i in params.indices) {
                paramNames.add(params[i])
            }
        }
        paramNames.add("timestamp=$currentTime")
        // 初始化待md5签名字符串
        val retVal = StringBuilder(postPath)
        for ((count, name) in paramNames.withIndex()) {
            if (count > 0) {
                retVal.append("&")
            } else {
                retVal.append("@")
            }
            retVal.append(name)
        }
        oldParamsJson = retVal.toString()
        return MD5Util.getStringMD5(oldParamsJson)
    }
}